package com.exonline.back.controller.manager;

import cn.hutool.core.util.IdUtil;
import com.exonline.commons.entity.Teacher;
import com.exonline.commons.base.IBaseService;
import com.exonline.commons.dao.DaoImpl;
import com.exonline.commons.dao.IDao;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 管理员模块M层
 * @author hbrj
 */
public class ManagerService implements IBaseService {
    // 引入数据访问对象
    ObjectMapper mapper = new ObjectMapper();
    IDao managerDao = new DaoImpl<>();

    /**
     * @desc 1.根据sql进行查询用户信息
     * @author hbrj
     */
    public List queryAll(String sql,int pageSize, int pageNo,Object...obj) throws SQLException {
        return managerDao.queryWithPagingAndConditions(sql,null,pageNo,pageSize,new MapListHandler(),obj);
    }

    /**
     * @desc 2.查询用户信息视图,获取全部用户的公共信息
     * @author hbrj
     */
    public List queryAll(int pageSize, int pageNo) throws SQLException {
        return managerDao.queryWithPagingAndConditions("SELECT * FROM userview",null,pageNo,pageSize,new MapListHandler());
    }
    /**
     * @desc 3.更新管理员用户信息
     * @author hbrj
     */
    @Override
    public void update(Object... obj) throws SQLException {
        managerDao.updateWithTransaction("update admin set name = ?,phone = ?,email = ? where id = ?", obj);
    }

    /**
     * @desc 4.查询指定用户,获取该用户详细信息
     * @author hbrj
     */
    @Override
    public Object queryOne(String field) throws SQLException {
        List<Map<String, Object>> stringMap = (List<Map<String, Object>>) managerDao.queryForObject("SELECT * FROM userview WHERE id = ? OR name like ?", new MapListHandler(), field, field + "%");
        return stringMap;
    }


    /**
     * @desc 5.根据id删除指定管理员
     * @author hbrj
     */
    @Override
    public void deleteById(String id) throws SQLException {
        managerDao.updateWithTransaction(" DELETE FROM admin WHERE id = ?",id);
    }
    /**
     * @desc 6.获取全部待审核教师信息
     * @author hbrj
     */
    public List<Teacher> queryAllReview(int pageSize, int pageno) throws SQLException {
        List<Teacher> teachers = managerDao.queryWithPagingAndConditions("SELECT * FROM reviewteacherview", null, pageno, pageSize, new BeanListHandler<>(Teacher.class), null);
        return teachers;
    }

    /**
     * @desc 7.根据sql条件,获取待审核教师的信息
     * @author hbrj
     */
    public List<Teacher> queryAllReview(String sql,int pageSize, int pageno,Object...obj) throws SQLException {
        List<Teacher> teachers = managerDao.queryWithPagingAndConditions(sql, null, pageno,  pageSize, new BeanListHandler<>(Teacher.class), obj);
        return teachers;
    }
    /**
     * 8.执行对教师的审核操作
     * @author hbrj
     */
    public void executeReview(String id, String tid, String aid, String comment, String status) throws SQLException {
        //7.1通过教师审核,更改教师通过状态
        if (status.equals("1")) {
            managerDao.updateWithTransaction("UPDATE teacher set status = 1 where id = ?",tid);
            managerDao.updateWithTransaction("INSERT INTO reviewhistory(id,tid,aid,status,comment) values(?,?,?,?,?)",id,tid,aid,"1",comment);
        }
        else{
            //7.2驳回教师审核,更新教师审核申请状态
            managerDao.updateWithTransaction("UPDATE teacher set status = 2 where id = ?",tid);
            managerDao.updateWithTransaction("INSERT INTO reviewhistory(id,tid,aid,status,comment) values(?,?,?,?,?)",id,tid,aid,"2",comment);
        }
    }
    /**
     * @desc 9.查询指定待审核教师的详细审核申请信息
     * @author hbrj
     */
    public Teacher queryOneReview(String sql,String id) throws SQLException {
        Teacher teacher = (Teacher) managerDao.queryForObject(sql, new BeanHandler<>(Teacher.class),id);
        return teacher;
    }

    public Map<String, Object> getStatusInfo() throws SQLException {
        Object watting = managerDao.queryCount("SELECT count(*) FROM teacher where status = 0");
        Object success = managerDao.queryCount("SELECT count(*) FROM teacher WHERE status = 1");
        Object refuse = managerDao.queryCount("SELECT count(*) FROM teacher WHERE status = 2");
        Map<String,Object> map = new HashMap<>();
        map.put("watting", watting);
        map.put("success", success);
        map.put("refuse", refuse);
        return map;
    }

    public String getRowCount(String sql) throws SQLException {
        int rowCount = managerDao.queryCount(sql);
        return String.valueOf(rowCount);
    }

    public void addUser(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        //todo 改这个别忘了
        //7.1获取要添加的用户的所有角色的公共属性
        String role = req.getParameter("role");
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        if (role == null || role.isEmpty() ||
                name == null || name.isEmpty() ||
                phone == null || phone.isEmpty() ||
                email == null || email.isEmpty() ||
                password == null || password.isEmpty()) {
            Map<String, Object> map = new HashMap<>();
            map.put("code", 201);
            map.put("msg", "添加错误,请输入合法字段");
            map.put("data", "error");
            mapper.writeValue(resp.getWriter(), map);
            //返回错误响应
        }
        String id = IdUtil.simpleUUID();
        try {
            //7.2当添加的用户为老师时,获取老师的特有参数
            if ("teacher".equals(role) || "老师".equals(role)) {
                String direction = req.getParameter("direction");
                String workyears = req.getParameter("workyears");
                String introduce = req.getParameter("introduce");
                this.add("INSERT INTO teacher(id,tname,workyears,direction,introduce,email,phone,password,status) VALUES(?,?,?,?,?,?,?,?,?)",id,name, workyears, direction, introduce, email, phone, password, 1);
                this.add("INSERT INTO userrole(id,rid,tid) VALUES(?,"+"'002'"+",?)",IdUtil.simpleUUID(),id);
            }
            //7.3当添加的用户为学生时,获取老师的特有参数
            else if (("student".equals(role) || "学生".equals(role))) {
                this.add("INSERT INTO student(id,sname,phone,email,password,status) values (?,?,?,?,?,?)",id, name, phone, email, password, 1);
                this.add("INSERT INTO userrole(id,rid,sid) VALUES(?,"+"'001'"+",?)",IdUtil.simpleUUID(),id);
            }
            //7.4当添加的用户为管理员时,获取管理员的特有参数条件
            else {
                String admintype = req.getParameter("admintype");
                String rid = "";
                //7.5根据需要添加的管理员角色,进行条件初始化
                switch (admintype){
                    case "金融审计员" -> {
                        rid = "005";
                    }
                    case "内容审核员" -> {
                        rid = "004";
                    }
                    case "超级管理员" -> {
                        rid = "003";
                    }
                }
                this.add("INSERT INTO admin(id,aname,phone,status,email,password) VALUES(?,?,?,?,?,?)",id,name, phone,password,1,email);
                this.add("INSERT INTO userrole(id,rid,aid) VALUES(?,?,?)",IdUtil.simpleUUID(),rid,id);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("code", 200);
            map.put("msg", "添加用户成功");
            map.put("data", id);
            mapper.writeValue(resp.getWriter(), map);
        } catch (SQLException e) {
            throw new SQLException("添加用户失败,可能是手机号重复" + e.getMessage());
        }
    }
}
